<template>
  <div class="custom-select">
    <el-select
      ref="customSelect"
      v-model="currentCode"
      :placeholder="placeholder"
      :disabled="disabled"
      :clearable="clearable"
      :filterable="filterable"
      :multiple="multiple"
      :collapse-tags="collapseTags"
      v-bind="$attrs"
      @change="customSelectChange"
      @visible-change="isShowSelectOptions"
      @clear="customClear"
    >
      <el-option
        v-for="(list, index) in selectOptions"
        :key="index"
        :label="list[bindName]"
        :value="list[bindValue]"
      />
    </el-select>
  </div>
</template>

<script>
import { getDictByType } from '@/api/dataDict'
export default {
  props: {
    placeholder: {
      type: String,
      default: '请输入'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    filterable: {
      type: Boolean,
      default: false
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 多选时是否将选中值按文字的形式展示
    collapseTags: {
      type: Boolean,
      default: false
    },
    // 回显或select value值
    echoValue: {
      type: [String, Number, Array],
      default: ''
    },
    echoName: {
      type: [String, Number, Array],
      default: ''
    },
    // 绑定的Label名称
    bindName: {
      type: [String, Array],
      default: ''
    },
    // 绑定的Label值
    bindValue: {
      type: [String, Array],
      default: ''
    },
    // 是否开启取额外参数，当 emit为空时，取全部OBJ数据
    isEmit: {
      type: Boolean,
      default: false
    },
    // 所取值集合，改参数需开启 isEmit
    emitArr: {
      type: Array,
      default: () => ([])
    },
    // 数据字典Code
    dictTypeCode: {
      type: String,
      default: 'RESPONSIBLE_DEPARTMENT'
    },
    // 当propEnum 不为空时，优先获取该配置的数据字典
    propEnum: {
      type: Object,
      default: () => ({})
    },
    // 当清空当前所选数据后的默认值
    defValue: {
      type: [String, Array, Object],
      default: ''
    },
    // 获取字典后过滤数据
    filterHandle: {
      type: Function,
      default: undefined
    }
  },
  data() {
    return {
      selectOptions: [],
      currentCode: ''
    }
  },
  watch: {
    echoValue: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.currentCode = newVal
        }
      },
      immediate: true,
      deep: true
    },
    dictTypeCode: {
      handler(nv, ov) {
        if (nv !== ov) this.getDictInfo()
      },
      immediate: false,
      deep: true
    }
  },
  created() {
  },
  mounted() {
    // const key = `marketing_call-center_${this.dictTypeCode}`
    // const dictList = getStore({ name: key }).sort((a, b) => { return a.sort - b.sort })
    // if (Array.isArray(dictList) && dictList.length) {
    //   if (this.dictTypeCode === 'PROCESS_RATE') {
    //     dictList.sort(this.arraySort('dictCode'))
    //   }
    //   this.selectOptions = dictList
    // }
    this.getDictInfo()
  },
  methods: {
    // 是否显示下拉框
    isShowSelectOptions(isShowSelectOptions) {
      if (!isShowSelectOptions) this.$refs.customSelect.blur()
    },
    // 获取数据字典信息
    getDictInfo(refresh) {
      if (refresh || Array.isArray(this.selectOptions) && this.selectOptions.length === 0) {
        let params = {}
        if (Object.keys(this.propEnum).length) {
          params = this.propEnum
        } else {
          params = { dictTypeCode: this.dictTypeCode, appCode: 'call-center', domainCode: 'marketing' }
        }
        getDictByType(params).then(response => {
          if (refresh || Array.isArray(response.data) && response.data.length) {
            // if (this.dictTypeCode === 'PROCESS_RATE') {
            //   response.data.sort(this.arraySort('dictCode'))
            // }
            if (this.filterHandle instanceof Function) {
              this.selectOptions = this.filterHandle(response.data)
            } else {
              this.selectOptions = response.data || []
            }
          }
        })
      }
    },
    customClear() {
      if (this.multiple) {
        this.$emit('update:echoValue', this.defValue)
      }
      this.$emit('on-change')
    },
    // 下拉框值改变时
    customSelectChange(val) {
      // 判断选择中是否为空
      if (val === '' || (Array.isArray(val) && val.length === 0)) {
        this.currentCode = val
        if (Array.isArray(this.selectOptions) && this.selectOptions.length) {
          const k = this.selectOptions[0]
          if (typeof k === 'object' && Object.keys(k).length) {
            Object.keys(k).forEach(key => {
              this.$emit(`update:${key}`, '')
            })
          }
          this.$emit('update:echoValue', this.defValue || '')
          this.$emit('update:echoName', '')
        }
        return
      }
      // 多选
      if (this.multiple) {
        if (Array.isArray(val) && val.length) {
          const selectArr = val.map(item => {
            const obj = this.selectOptions.find(list => {
              return list[this.bindValue] === item
            })
            return obj
          })
          if (selectArr.length) {
            const keyArr = Object.keys(selectArr[0])
            const obj = {}
            selectArr.forEach(list => {
              keyArr.forEach(k => {
                obj[k] ? obj[k] += `,${list[k]}` : obj[k] = `${list[k]}`
              })
            })
            if (typeof obj === 'object' && Object.keys(obj).length) {
              if (this.isEmit) {
                if (Array.isArray(this.emitArr) && this.emitArr.length) {
                  this.emitArr.forEach(k => {
                    this.$emit(`update:${k}`, obj[k])
                  })
                } else {
                  Object.keys(obj).forEach(key => {
                    this.$emit(`update:${key}`, obj[key])
                  })
                }
              }
              this.$emit('update:echoValue', obj[this.bindValue].split(','))
              this.$emit('update:echoName', obj[this.bindName])
            }
          }
        }
      }
      // 下拉框单选
      if (!this.multiple) {
        const obj = this.selectOptions.find(list => {
          return list[this.bindValue] === val
        })
        if (typeof obj === 'object' && Object.keys(obj).length) {
          if (this.isEmit) {
            if (Array.isArray(this.emitArr) && this.emitArr.length) {
              this.emitArr.forEach(k => {
                this.$emit(`update:${k}`, obj[k])
              })
            } else {
              Object.keys(obj).forEach(key => {
                this.$emit(`update:${key}`, obj[key])
              })
            }
          }
          this.$emit('update:echoValue', obj[this.bindValue])
          this.$emit('update:echoName', obj[this.bindName])
          this.$emit('on-change', obj)
        }
      }
    },
    /**
     * Object类型数组排序
     */
    arraySort(field) {
      return (a, b) => {
        const val1 = a[field]
        const val2 = b[field]
        return val1 - val2
      }
    }
  }
}
</script>

<style lang="less" scoped>
.custom-select {
  /deep/ .el-select {
    width: 100%;
  }
}
</style>
